package com.springboot.distributed;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.springboot.common.util.StringUtil;

import io.seata.rm.datasource.DataSourceProxy;
import io.seata.spring.annotation.GlobalTransactionScanner;
import lombok.extern.log4j.Log4j2;

/**
 * 配置fescar以及数据库代理
 * @author supu
 * @date 2019-09-03 14:55
 */
@Log4j2
@Configuration
public class SeataConfig {
    @Value("${spring.application.name}")
    private String applicationName;
    @Value("${tx.service.group}")
    private String txServiceGroup;

    /**
     * 数据源配置
     *
     * @return
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    /**
     * 启用fescar的数据库代理
     * @param dataSource
     * @return
     */
    @Bean
    public DataSourceProxy dataSourceProxy(DataSource dataSource) {
        return new DataSourceProxy(dataSource);
    }

    /**
     * SqlSessionFactory 配置
     * init mybatis sqlSessionFactory
     * @param dataSourceProxy
     * @return
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSourceProxy);
        factoryBean.setTransactionFactory(new JdbcTransactionFactory());
        return factoryBean.getObject();
    }

    /**
     * init global transaction scanner
     * @return
     */
    @Bean
    public GlobalTransactionScanner globalTransactionScanner() throws Exception {
        if (StringUtil.isAnyBlank(applicationName, txServiceGroup)) {
            throw new Exception("请配置 spring.application.name or tx.service.group!");
        }
        return new GlobalTransactionScanner(applicationName, txServiceGroup);
    }
}
